<?php

namespace addons\JhxEdu\api\modules\v1\controllers\order;

use Yii;
use common\helpers\Url;
use yii\data\ActiveDataProvider;
use yii\helpers\Json;
use common\helpers\ResultHelper;
use common\enums\StatusEnum;
use common\enums\PayTypeEnum;
use common\helpers\AddonHelper;
use addons\JhxEdu\common\models\order\Order;
use addons\JhxEdu\common\models\order\OrderProduct;
use addons\JhxEdu\common\models\product\Product;
use api\controllers\OnAuthController;
use common\models\forms\PayForm;
use addons\JhxEdu\common\models\forms\OrderPayFrom;

/**
 * 产品
 *
 * Class ProductController
 * @package addons\JhxEdu\api\modules\v1\controllers\order
 */
class OrderController extends OnAuthController
{
    /**
     * @var Product
     */
    public $modelClass = Order::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = [];

    /**
     * 通过课程id计算价格，并返回商品信息，作为确认订单数据
     * @return mix
     */
    public function actionProductCalc()
    {
        $member = !Yii::$app->user->isGuest ? Yii::$app->user->identity->member : '';
        $is_vip = Yii::$app->jhxEduService->member->isVip($member);
        $product_id = Yii::$app->request->get('product_id');
        if(is_array($product_id))
            $product = Product::find()->where(['id'=>$product_id])->All();
        else
            $product = Product::find()->where(['id'=>$product_id])->limit(1)->All();
        if(empty($product)){
            return ResultHelper::json(422, '课程不存在');
        }
        $money = Yii::$app->jhxEduService->order->productPrice($product);

        return ['product'=>$product,'money'=>$money,'is_vip'=>$is_vip];
    }
     /**
     * 创建订单
     *
     * @return Order|mixed|\yii\db\ActiveRecord
     * @throws \yii\web\NotFoundHttpException
     * @throws \yii\web\UnprocessableEntityHttpException
     */
    public function actionCreate()
    {
        /** @var AccessToken $identity */
        /** @var PreviewForm $model */
        $identity = Yii::$app->user->identity;
        $model = new Order();
        $orderProduct = new OrderProduct();
        $model->setScenario('create');
        $model->attributes = Yii::$app->request->post();
        $model->products_id = json_decode(Yii::$app->request->post('products_id'));
        $model->member_id = $identity->member_id;
        $transaction = Yii::$app->db->beginTransaction();
        $config = AddonHelper::getConfig();
        try {
            // 订单来源
            $model->order_from = $identity->group;
            $order = Yii::$app->jhxEduService->order->create($model);
            $transaction->commit();
            //在这里判断，如果仅使用微信支付时，直接返回微信支付唤起参数
            if(isset($config['edu_pay_method']) && $config['edu_pay_method'] == 1){
                $payForm =  new PayForm();
                $payForm->attributes = Yii::$app->request->post();
                $payForm->member_id = $identity->member_id;
                $payForm->order_group = 'order';
                $payForm->data['order_id'] = $order->id;
                $payForm->setHandlers([
                    'order' => OrderPayFrom::class,
                ]);
                // 回调方法
                $payForm->pay_type = PayTypeEnum::WECHAT; //微信支付
                $payForm->notify_url = Url::removeMerchantIdUrl('toFront', ['notify/' . PayTypeEnum::action($payForm->pay_type)]);
                !$payForm->openid && $payForm->openid = Yii::$app->user->identity->openid;
                // 生成配置
                $rs = $payForm->getConfig();
                return ResultHelper::json(200, '待支付', [
                    'payStatus' => false,
                    'onlyWx' => true,
                    'config' => $rs,
                ]);
            }
            return $order;
        } catch (\Exception $e) {
            $transaction->rollBack();

            return ResultHelper::json(422, $e->getMessage());
        }
    }
    public function actionVipCreate(){
        /** @var AccessToken $identity */
        /** @var PreviewForm $model */
        $identity = Yii::$app->user->identity;
        $model = new Order();
        $orderProduct = new OrderProduct();
        $model->setScenario('create');
        $model->attributes = Yii::$app->request->post();
        $model->products_id = json_decode(Yii::$app->request->post('products_id'));
        $model->member_id = $identity->member_id;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            // 订单来源
            $model->order_from = $identity->group;
            $order = Yii::$app->jhxEduService->order->vipCreate($model);
            $transaction->commit();
            //在这里判断，如果仅使用微信支付时，直接返回微信支付唤起参数
            if('onlyWx'){
                $payForm =  new PayForm();
                $payForm->attributes = Yii::$app->request->post();
                $payForm->member_id = $identity->member_id;
                $payForm->order_group = 'vip';
                $payForm->data['order_id'] = $order->id;
                $payForm->setHandlers([
                    'vip' => OrderPayFrom::class,
                ]);
                // 回调方法
                $payForm->pay_type = PayTypeEnum::WECHAT; //微信支付
                $payForm->notify_url = Url::removeMerchantIdUrl('toFront', ['notify/' . PayTypeEnum::action($payForm->pay_type)]);
                !$payForm->openid && $payForm->openid = Yii::$app->user->identity->openid;
                // 生成配置
                $rs = $payForm->getConfig();
              
                return ResultHelper::json(200, '待支付', [
                    'payStatus' => false,
                    'onlyWx' => true,
                    'config' => $rs,
                ]);
            }
            return $order;
        } catch (\Exception $e) {
            $transaction->rollBack();

            return ResultHelper::json(422, $e->getMessage());
        }
    }
    /**
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionView($id)
    {
        // 判断用户
        $member_id = !Yii::$app->user->isGuest ? Yii::$app->user->identity->member_id : '';

        $model = Yii::$app->jhxEduService->product->findViewById($id, $member_id);
        
        if (!$model) {
            return ResultHelper::json(422, '商品找不到了');
        }

        if ($model['product_status'] == StatusEnum::DISABLED) {
            return ResultHelper::json(422, '商品已下架');
        }
        // 浏览量 + 1
        Product::updateAllCounters(['view' => 1], ['id' => $id]);
        // 足迹
        //!empty($member_id) && Yii::$app->tinyShopService->memberFootprint->create($model, $member_id);
        // 评论
        if (!empty($model['evaluate'])) {
            foreach ($model['evaluate'] as &$datum) {
                empty($datum['again_covers']) && $datum['again_covers'] = [];
                !is_array($datum['again_covers']) && $datum['again_covers'] = Json::decode($datum['again_covers']);
                empty($datum['covers']) && $datum['covers'] = [];
                !is_array($datum['covers']) && $datum['covers'] = Json::decode($datum['covers']);
                // 匿名
                if ($datum['is_anonymous'] == StatusEnum::ENABLED) {
                    $datum['member_id'] = '';
                    $datum['member_nickname'] = '';
                    $datum['member_head_portrait'] = '';
                }
            }
        }
        return $model;
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, ['delete', 'update'])) {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}